/*
 * @lc app=leetcode.cn id=329 lang=java
 *
 * [329] 矩阵中的最长递增路径
 */

// @lc code=start
class Solution {

    public int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    public int rows, columns;

    public int longestIncreasingPath(int[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return 0;
        }

        rows = matrix.length;
        columns = matrix[0].length;

        int[][] memo = new int[rows][columns];
        int res = 0;
        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < columns; j++) {
                res = Math.max(res, dfs(matrix, i, j, memo));
            }
        }
        return res;
    }

    public int dfs(int[][] matrix, int i, int j, int[][] memo) {
        if(memo[i][j] != 0) {
            return memo[i][j];
        }

        memo[i][j]++;
        for(int[] dir : dirs) {
            int newRow = i + dir[0];
            int newColumn = j + dir[1];
            if(newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns && matrix[newRow][newColumn] > matrix[i][j]) {
                memo[i][j] = Math.max(memo[i][j], dfs(matrix, newRow, newColumn, memo) + 1);
            }
        }
        return memo[i][j];
    }
}
// @lc code=end

